<?php
// +-------------------------------------------------------------------------------
// | DingZone [ A Rapid Development Framework For Dingtalk ]
// +-------------------------------------------------------------------------------
// | TaskConfig.php v1.0
// |
// | Copyright (c) 2014-2018 http://www.heimalanshi.com All rights reserved.
// | Author : Jie
// | Date : 2018-09-30
// +-------------------------------------------------------------------------------


namespace app\core\model;

use think\Db;
use think\Log;

class CronTask {
    const NORMAL = 1;
    const PAUSE = 0;

    public static function _q() {
        return Db::name("cron_task");
    }

    /**
     * 根据任务id获取任务配置信息
     *
     * @param $taskId
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getById($taskId) {
        return self::_q()->where([
            'id' => $taskId
        ])->find();
    }

    /**
     * 添加日志
     *
     * @param $cronTask
     * @param $msg
     */
    public static function addLog($cronTask, $msg) {
        Log::record("[" . $cronTask['module'] . " - " . $cronTask['name'] . "] " . date('Y-m-d H:i:s') . " " . $msg, "task");
    }


    /**
     * 检查任务是否正在运行
     *
     * @param $moduleName
     * @param $taskName
     * @return bool
     */
    public static function isTaskRunning($moduleName, $taskName) {
        $cacheKey = self::getTaskRunningCacheKey($moduleName, $taskName);

        if ($cacheKey->getValue()) {
            return true;
        }
        return false;
    }

    /**
     * 记录任务正在运行
     *
     * @param $moduleName
     * @param $taskName
     * @param int $expire
     */
    public static function taskRunning($moduleName, $taskName, $expire = 3600) {
        $cacheKey = self::getTaskRunningCacheKey($moduleName, $taskName);
        $cacheKey->setValue(true, $expire);
    }

    /**
     * 任务执行完毕
     *
     * @param $moduleName
     * @param $taskName
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function taskFinish($moduleName, $taskName) {
        $cacheKey = self::getTaskRunningCacheKey($moduleName, $taskName);
        $cacheKey->deleteValue();
    }

    /**
     * 获取任务正在运行缓存key
     *
     * @param $moduleName
     * @param $taskName
     * @return CacheKey
     */
    public static function getTaskRunningCacheKey($moduleName, $taskName) {
        $cacheKey = CacheKey::module("core")->type("TaskOverlap")->tags([
            'module' => $moduleName,
            'name' => $taskName
        ]);
        return $cacheKey;
    }

    /**
     * 创建模块任务配置
     *
     * @param $moduleName
     * @param $tasks
     */
    public static function createModuleTasks($moduleName, $tasks) {
        foreach ($tasks as $task) {
            self::_q()->insertGetId([
                'module' => $moduleName,
                'name' => $task['name'],
                'title' => $task['title'],
                'state' => self::NORMAL,
                'cron' => $task['cron'],
                'timeout' => $task['timeout'],
                'overlap' => $task['overlap']
            ]);
        }
    }

    /**
     * 删除模块任务配置
     *
     * @param $moduleName
     * @return int
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function deleteModuleTasks($moduleName) {
        return self::_q()->where([
            'module' => $moduleName
        ])->delete();
    }

    /**
     * 更新任务
     * @param $id
     * @param $title
     * @param $state
     * @param $cron
     * @param $timeout
     * @param $overlap
     * @return int|string
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function updateTask($id, $title, $state, $cron, $timeout, $overlap) {
        return self::_q()->where([
            'id' => $id
        ])->update([
            'title' => $title,
            'state' => $state,
            'cron' => $cron,
            'timeout' => $timeout,
            'overlap' => $overlap
        ]);
    }
}